//
//  ChatCell.m
//  WChat
//
//  Created by lw on 2018/7/31.
//  Copyright © 2018年 mjsfax. All rights reserved.
//

#import "ChatCell.h"
#import <UIImageView+WebCache.h>
#import "EMCDDeviceManager.h"

@interface ChatCell()
@property (weak, nonatomic) IBOutlet UILabel *lbContentText;
@property (weak, nonatomic) IBOutlet UIButton *btnPlay;
@property (strong, nonatomic) UIImageView *contentImage;
@end

@implementation ChatCell

+ (instancetype)cellWithTableView:(UITableView *)tableView {
    ChatCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatCell"];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"ChatCell" owner:self options:nil].firstObject;
    }
    return cell;
}

- (void)setModel:(ChatModel *)model {
    _model = model;
    self.lbContentText.text = nil;
    self.btnPlay.hidden = !(model.chatType == ChatTypeVoice);
    
    if (self.contentImage) {
        [self.contentImage removeFromSuperview];
        self.contentImage = nil;
    }
    switch (model.chatType) {
        case ChatTypeText:{
            self.lbContentText.text = model.contentText;
            self.lbContentText.textAlignment = model.isMe ? NSTextAlignmentRight : NSTextAlignmentLeft;
        }
            break;
        case ChatTypeImage: {
            [self addSubview:self.contentImage];
            if (model.localThumbnailUrl) {
                self.contentImage.frame = model.imageRect;
                self.contentImage.image = [UIImage imageWithContentsOfFile:model.localThumbnailUrl];
            } else {
                [self.contentImage sd_setImageWithURL:[NSURL URLWithString:model.remoteThumbnailUrl] placeholderImage:[UIImage imageNamed:@"pl"]];
            }
        }
            break;
        case ChatTypeVoice: {
            [self.btnPlay setTitle:[NSString stringWithFormat:@"语音%zd",model.duration] forState:UIControlStateNormal];
        }
            break;
        default:
            break;
    }
    
}
- (IBAction)play:(UIButton *)sender {
    if ([[EMCDDeviceManager sharedInstance] isPlaying]) {
        [[EMCDDeviceManager sharedInstance] stopPlaying];
    }
    [[EMCDDeviceManager sharedInstance] asyncPlayingWithPath:self.model.voicePath completion:^(NSError *error) {
        if (error) {
            NSLog(@"%@",error);
            return;
        }
        NSLog(@"播放。。。");
    }];
}

- (void)click {
    if (self.actionBlock) {
        self.actionBlock(self.model.chatType);
    }
}

- (UIImageView *)contentImage {
    if (!_contentImage) {
        _contentImage = [[UIImageView alloc] init];
        _contentImage.userInteractionEnabled = YES;
        UITapGestureRecognizer *tab = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click)];
        [_contentImage addGestureRecognizer:tab];
    }
    return _contentImage;
}

@end
